<script setup>
import {
  ElButton,
  ElRow,
  ElCol,
  ElTag,
  ElMessage,
  ElAlert,
} from "element-plus";
import {
  equityInvestReport,
  equityInvestReportDetails,
  equityInvestEditDetail,
  equityInvestDeleteInvestDetail,
} from "@/api/investPaper/";
import CustomModal from "@/components/CustomModal/";
import {
  getCurentDate,
  transformNumber,
  toPercent,
  endsWithAny,
} from "@/hooks/useCommon";
import { ref, computed, watchEffect, onMounted } from "vue";
import CustomTable from "@/components/CustomTable";
import { useUpload } from "@/hooks/useUpload";
import PreviewPdf from "@/components/PreviewPdf";
import { recordType } from '@/common/dict/dictCollect'

const props = defineProps({
  init: { type: Object, default: () => ({}) },
  visible: { type: Boolean, default: false },
});
const emit = defineEmits(["update:visible", "finish"]);
const open = computed({
  get() {
    return props.visible;
  },
  set(val) {
    emit("update:visible", val);
  },
});
const columns = [
  {
    label: "款项名称",
    prop: "itemName",
    minWidth: 150,
  },
  {
    label: "记录类型",
    prop: "type",
    minWidth: 150,
    formatter: (text) => recordType[text]
  },
  {
    label: "支付金额（元）",
    minWidth: 150,
    prop: "paymentAmount",
    formatter: (t, r) => transformNumber(r.paymentAmount),
  },
  {
    label: "付款时间",
    minWidth: 150,

    prop: "paymentTime",
  },
  {
    label: "支付凭证",
    prop: "paymentFileUrl",
    minWidth: 200,
    slot: true,
  },
  {
    label: "填报人/时间",
    minWidth: 200,
    prop: "createUserName",

    formatter: (t, r) => `${r.createUserName || "-"}/${r.createTime || "-"}`,
  },
];
const rules = {
  nextMonthWork: [
    { required: true, message: "请输入下月工作安排", trigger: "blur" },
  ],
  importantWork: [
    { required: true, message: "请输入本月重点工作", trigger: "blur" },
  ],
};
const { curDay, curMonth, curYear } = getCurentDate();

const currentMonth = computed(() => (curDay > 7 ? curMonth + 1 : curMonth - 1));

const edits = ref({});
const form = ref();
const dataSource = ref([]);
const previewVisible = ref(false);
const previewUrl = ref("");
const allInfo = ref({});

const getMonthDetails = async () => {
  const { data } = await equityInvestReportDetails({
    month: props.init.month,
    year: curYear,
    equityProjectId: props.init.equityProjectId,
  });
  const { details = [], importantWork, nextMonthWork, totalAmount } = data;

  dataSource.value = details.map((_) => ({
    ..._,
    paymentFileUrl: _.paymentFileUrl
      ? [{ name: _.paymentFileName, url: _.paymentFileUrl }]
      : [],
  }));

  allInfo.value = {
    importantWork,
    nextMonthWork,
    totalAmount,
  };
};

const handlePreview = (row) => {
  const [file] = row.paymentFileUrl || [];
  if(row.type === 'USER') {
    if (!file) return ElMessage.error("请上传文件")
    previewUrl.value = file.url;
    previewVisible.value = true;
  }else {
    if (!file) return
    window.open(file.url, '_blank')
  }
}

const handleFinish = (flag = false) => {
  emit("finish");
  open.value = flag;
};
watchEffect(() => open.value && getMonthDetails());
</script>

<template>
  <CustomModal
    teleport="#app"
    width="60%"
    :title="`${props.init.month}月支付明细`"
    v-model:visible="open"
    :footerButton="false"
  >
    <el-form
      ref="form"
      label-position="top"
      label-width="auto"
      :model="edits"
      :rules="rules"
    >
      <br />
      <el-row :gutter="10">
        <el-col :span="2">
          <!-- <el-tag size="large" type="warning"
            >当前填报月份{{ currentMonth }}月</el-tag
          > -->
        </el-col>
        <el-col :span="2" :offset="19"> </el-col>
      </el-row>
      <br />
      <el-form-item>
        <CustomTable
          border
          index
          :height="dataSource?.length > 2 ? '35vh' : '100%'"
          style="width: 100%"
          :tableData="dataSource"
          :tableOption.sync="columns"
          :isPaging="false"
        >
          <template
            v-for="column in columns"
            #[column.prop]="scope"
            :key="column.prop"
          >
            <el-button
              v-if="column.prop === 'paymentFileUrl'"
              :disabled="!scope.row?.paymentFileUrl.length"
              link
              @click="handlePreview(scope.row)"
            >
              {{
                scope.row?.paymentFileUrl.length
                  ? scope.row?.type === 'USER' ? `预览（${scope.row?.paymentFileUrl[0]?.name}）` : '查看审批'
                  : "-"
              }}
            </el-button>
            <span v-else>{{ scope.row[column.prop] || "-" }}</span>
          </template>
        </CustomTable>
        <h3 v-if="allInfo.totalAmount">合计{{ allInfo.totalAmount }}万元</h3>
      </el-form-item>

      <el-form-item label="本月工作重点" prop="importantWork">
        {{ allInfo.importantWork || "-" }}
      </el-form-item>
      <el-form-item label="下月工作安排" prop="nextMonthWork">
        {{ allInfo.nextMonthWork || "-" }}
      </el-form-item>
    </el-form>
  </CustomModal>

  <el-dialog v-model="previewVisible">
    <div class="dialog_content">
      <img
        v-if="endsWithAny(previewUrl, ['.jpg', '.png', '.jpeg'])"
        style="width: 100%"
        w-full
        :src="previewUrl"
        alt="图片预览"
      />
      <PreviewPdf v-if="previewUrl.endsWith('.pdf')" :url="previewUrl" />
    </div>
  </el-dialog>
</template>

<style scoped></style>
